package com.study.spring.hadoop.hdfs;

import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.Path;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.hadoop.fs.FsShell;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

public class FsShellDemo {

    @Autowired
    FsShell shell;

    /**
     * （1）返回hdfs路径下的文件信息
     * @param path
     * @return
     * @throws Exception
     */
    public List<HdfsFile> listPaths(String path) throws Exception{
        Collection<FileStatus> fileStatuses = shell.lsr(path);

        List<HdfsFile> fileList = new ArrayList<>();

        for(FileStatus fs: fileStatuses){
            boolean isDirectory = fs.isDirectory();

            if (!isDirectory){
                Path hdfsPath = fs.getPath();
                String name = hdfsPath.getName();
                String uri = hdfsPath.toUri().getPath();

                String owner = fs.getOwner();
                long blockSize = fs.getBlockSize();

                HdfsFile file = new HdfsFile();
                file.setFileOwner(owner);
                file.setFileName(name);
                file.setBlockSize(blockSize);
                file.setFilePath(uri);

                fileList.add(file);
            }
        }
        return fileList;
    }
    /**
     * （2）创建hdfs目录
     */
    public Boolean mkDir(String path){
        try {
            shell.mkdir(path);
        } catch (Exception e){
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     *  上传文件
     */
    public Boolean putFile(String srcPath , String destPath){
        try {
            shell.put(srcPath , destPath);
        } catch (Exception e){
            e.printStackTrace();
            return false;
        }
        return true;
    }


    /**
     * 下载文件
     * @param srcPath
     * @param destPath
     * @return
     */
    public Boolean getFile(String srcPath , String destPath){
        try {
            shell.get(srcPath , destPath);
        } catch (Exception e){
            e.printStackTrace();
            return false;
        }
        return true;
    }
}
